
package GUI;

import user.User;
import utilities.SpringUtilities;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import controller.LoginManager;

public class Login extends JFrame{
    public Login(){
        JLabel l1 = new JLabel("Username: ");
        userName = new JTextField(10);
        JLabel l2 = new JLabel("Password: ");
        password = new JTextField(10);
        JPanel p = new JPanel(new SpringLayout());
        p.add(l1);
        p.add(userName);
        p.add(l2);
        p.add(password);
        SpringUtilities.makeCompactGrid(p, 2, 2, 30, 20, 3, 2);
        JButton login = new JButton("Login");
        login.addActionListener(new LoginListener());
        JPanel global = new JPanel();
        global.add(p);
        global.add(login);
        this.setLayout(new BorderLayout());
        this.add(global, BorderLayout.CENTER);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((int)screen.getWidth()/2-140, (int)screen.getHeight()/2-100);
        this.setSize(250, 160);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public class LoginListener implements ActionListener{
    	
        public void actionPerformed(ActionEvent e) {
        	User user = LoginManager.login(userName.getText(), password.getText());
        	if(user != null){
	        	JFrame m = new TopLevelFrame(); //apre la finestra mappa
	            m.setLocation(250, 150);
	            m.setVisible(true);
	            Login.this.dispose(); //chiudo il login
        	}else{
        		userName.setText("");
        		password.setText("");
        	}
        }

    }

    private JTextField userName, password;
}
